

import UIKit
import Contacts
func ==(lhs: Friend, rhs: Friend) -> Bool{
	return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName && lhs.workEmail == rhs.workEmail && lhs.profilePicture == rhs.profilePicture
}

struct Friend: Equatable{
	let firstName: String
	let lastName: String
	let workEmail: String
	let profilePicture: UIImage?
	
	init(firstName: String, lastName: String, workEmail: String, profilePicture: UIImage?){
		self.firstName = firstName
		self.lastName = lastName
		self.workEmail = workEmail
		self.profilePicture = profilePicture
	}
	
	static func defaultContacts() -> [Friend] {
		return [Friend(firstName: "Mic", lastName: "Pringle", workEmail: "mic@example.com", profilePicture: UIImage(named: "MicProfilePicture")), Friend(firstName: "Ray", lastName: "Wenderlich", workEmail: "ray@example.com", profilePicture: UIImage(named: "RayProfilePicture")), Friend(firstName: "Sam", lastName: "Davies", workEmail: "sam@example.com", profilePicture: UIImage(named: "SamProfilePicture")), Friend(firstName: "Greg", lastName: "Heo", workEmail: "greg@example.com", profilePicture: UIImage(named: "GregProfilePicture"))]
	}
}

extension Friend{
    var contactValue:CNContact{
//        1
        let contact = CNMutableContact()
//        2
        contact.givenName = firstName
        contact.familyName = lastName
//        3
        contact.emailAddresses = [CNLabeledValue(label: CNLabelWork, value: workEmail)]
//        4
        if let profilePicture = profilePicture{
            
            let imageData = UIImageJPEGRepresentation(profilePicture, 1)
                contact.imageData = imageData
            }
//         5
     return contact.copy() as! CNContact
    }
    
    
}

extension Friend{
    init(contact:CNContact){
        firstName = contact.givenName
        lastName = contact.familyName
        workEmail = contact.emailAddresses.first?.value as! String
        if let imagedata = contact.imageData{
            profilePicture = UIImage(data: imagedata)
        }else{
            profilePicture = nil
        }
    }
}